package com.huadao.cart_ccs.experiment.paramsSetting;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;

import com.huadao.cart_ccs.R;
import com.huadao.cart_ccs.base.BaseDialogFragment;
import com.huadao.cart_ccs.base.BasePresenter;
import com.huadao.cart_ccs.common.ParamsPreferences;
import com.huadao.cart_ccs.common.UtilHelpers;
import com.huadao.cart_ccs.common.inputControl.MaxDecimalTextWatch;
import com.huadao.cart_ccs.common.inputControl.MaxNumberTextWatch;
import com.huadao.cart_ccs.common.inputControl.NumberMaxAttention;
import com.huadao.cart_ccs.common.popwindow.RockPop;
import com.huadao.cart_ccs.data.bo.CO2BO;
import com.huadao.cart_ccs.data.bo.O2BO;
import com.huadao.cart_ccs.data.bo.PeristalticPumpBO;
import com.huadao.cart_ccs.data.bo.TemperatureBO;
import com.huadao.cart_ccs.experiment.home.ExperimentActivity;

import java.util.Date;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class SetParamsDF extends BaseDialogFragment implements SetParamsContract.ISetParamsView, NumberMaxAttention {
    @BindView(R.id.et_CO2)
    EditText etCO2;
    @BindView(R.id.et_O2)
    EditText etO2;
    @BindView(R.id.et_temperature)
    EditText etTemperature;
    @BindView(R.id.et_pump_fluidIntake_speed)
    EditText etPumpFluidIntakeSpeed;
    @BindView(R.id.sp_pump_fluidIntake_direction)
    Spinner spPumpFluidIntakeDirection;
    @BindView(R.id.et_pump_circulating_speed)
    EditText etPumpCirculatingSpeed;
    @BindView(R.id.sp_pump_circulating_direction)
    Spinner spPumpCirculatingDirection;
    @BindView(R.id.et_pump_waste_speed)
    EditText etPumpWasteSpeed;
    @BindView(R.id.sp_pump_waste_direction)
    Spinner spPumpWasteDirection;
    @BindView(R.id.et_pump_reclaim_speed)
    EditText etPumpReclaimSpeed;
    @BindView(R.id.sp_pump_reclaim_direction)
    Spinner spPumpReclaimDirection;
    @BindView(R.id.et_magnetic_stirrer_speed)
    EditText etMagneticStirrerSpeed;
    @BindView(R.id.et_cultureTank_speed)
    EditText etCultureTankSpeed;
    @BindView(R.id.et_changeAir_frequency)
    EditText etChangeAirFrequency;
    @BindView(R.id.et_changeAir_amount)
    EditText etChangeAirAmount;
    @BindView(R.id.et_shakeTable_time)
    EditText etShakeTableTime;
    @BindView(R.id.btn_goto_culture)
    Button btn_goto_culture;
    @BindView(R.id.btn_edit_environment)
    Button btn_edit_environment;
    @BindView(R.id.btn_set_environment)
    Button btn_set_environment;
    @BindView(R.id.edit_device_params)
    Button btn_edit_device_params;
    @BindView(R.id.save_device_params)
    Button save_device_params;

    private boolean isEnvironmentSetted;
    private boolean isDeviceParamsSetted;
    private RockPop rockPop;
    private Disposable popDisposable;
    private EditText oldEditText;

    private SetParamsContract.ISetParamsPresenter paramsPresenter;

    @Override
    protected BasePresenter getPresenter() {
        return paramsPresenter;
//        return null;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.dialog_devices_setparams;
    }

    @Override
    protected void onInit() {
        if(getActivity() instanceof SetParamsActivity){
            btn_goto_culture.setVisibility(View.VISIBLE);
            setLeftTopIconsVisibility(View.INVISIBLE);
        }else {
            btn_goto_culture.setVisibility(View.GONE);
            setLeftTopIconsVisibility(View.VISIBLE);
        }

        paramsPresenter = new SetParamsPresenter(this);

        setTitle(getString(R.string.params_setting));
        setSetIconsVisibility(View.INVISIBLE);

        String CO2 = String.valueOf(paramsPresenter.getDefaultCO2());
        etCO2.setText(CO2);
        etCO2.setSelection(CO2.length());
        etCO2.addTextChangedListener(new MaxDecimalTextWatch(ParamConsts.maxCO2, 2,etCO2,false,this));

        String O2 = String.valueOf(paramsPresenter.getDefaultO2());
        etO2.setText(O2);
        etO2.setSelection(O2.length());
        etO2.addTextChangedListener(new MaxDecimalTextWatch(ParamConsts.maxO2, 2, etO2,false,this));

        String temperature = String.valueOf(paramsPresenter.getDefaultTemperature());
        etTemperature.setText(temperature);
        etTemperature.setSelection(temperature.length());
        etTemperature.addTextChangedListener(new MaxDecimalTextWatch(ParamConsts.maxTemperature, 2, etTemperature,false,this));

        String fluidIntakePumpSpeed = String.valueOf(ParamsPreferences.getInstance().getFluidIntakePumpSpeed());
        etPumpFluidIntakeSpeed.setText(fluidIntakePumpSpeed);
        etPumpFluidIntakeSpeed.setSelection(fluidIntakePumpSpeed.length());
        etPumpFluidIntakeSpeed.addTextChangedListener(new MaxNumberTextWatch(ParamConsts.maxPumpSpeed, etPumpFluidIntakeSpeed, false, this));

        String circulatingPumpSpeed = String.valueOf(ParamsPreferences.getInstance().getCirculatingPumpSpeed());
        etPumpCirculatingSpeed.setText(circulatingPumpSpeed);
        etPumpCirculatingSpeed.setSelection(circulatingPumpSpeed.length());
        etPumpCirculatingSpeed.addTextChangedListener(new MaxNumberTextWatch(ParamConsts.maxPumpSpeed, etPumpCirculatingSpeed, false, this));

        String wastePumpSpeed = String.valueOf(ParamsPreferences.getInstance().getWastePumpSpeed());
        etPumpWasteSpeed.setText(wastePumpSpeed);
        etPumpWasteSpeed.setSelection(wastePumpSpeed.length());
        etPumpWasteSpeed.addTextChangedListener(new MaxNumberTextWatch(ParamConsts.maxPumpSpeed, etPumpWasteSpeed, false, this));

        String reclaimPumpSpeed = String.valueOf(ParamsPreferences.getInstance().getReclaimPumpSpeed());
        etPumpReclaimSpeed.setText(reclaimPumpSpeed);
        etPumpReclaimSpeed.setSelection(reclaimPumpSpeed.length());
        etPumpReclaimSpeed.addTextChangedListener(new MaxNumberTextWatch(ParamConsts.maxPumpSpeed, etPumpReclaimSpeed, false, this));

        spPumpFluidIntakeDirection.setSelection(getPosition(ParamsPreferences.getInstance().getFluidIntakePumpDirection()));

        spPumpCirculatingDirection.setSelection(getPosition(ParamsPreferences.getInstance().getCirculatingPumpDirection()));

        spPumpWasteDirection.setSelection(getPosition(ParamsPreferences.getInstance().getWastePumpDirection()));

        spPumpReclaimDirection.setSelection(getPosition(ParamsPreferences.getInstance().getReclaimPumpDirection()));

        String stirrerSpeed = String.valueOf(ParamsPreferences.getInstance().getStirrerSpeed());
        etMagneticStirrerSpeed.setText(stirrerSpeed);
        etMagneticStirrerSpeed.setSelection(stirrerSpeed.length());
        etMagneticStirrerSpeed.addTextChangedListener(new MaxNumberTextWatch(ParamConsts.maxStirrerSpeed, etMagneticStirrerSpeed, false, this));

        //换气固定转速50，持续时间4分钟
        String cultureTankSpeed = String.valueOf(ParamsPreferences.getInstance().getCultureTankSpeed());
        etCultureTankSpeed.setText(cultureTankSpeed);
        etCultureTankSpeed.setSelection(cultureTankSpeed.length());
        etCultureTankSpeed.addTextChangedListener(new MaxNumberTextWatch(100, etCultureTankSpeed, false, this));

        String changeAirFrequency= String.valueOf(ParamsPreferences.getInstance().getChangeAirFrequency()/60);
        String changeAirAmount= String.valueOf(ParamsPreferences.getInstance().getChangeAirAmount());
        etChangeAirAmount.setText(changeAirAmount);
        etChangeAirFrequency.setText(changeAirFrequency);

        etShakeTableTime.setText(String.valueOf(ParamsPreferences.getInstance().getShakeTableTime()));

        //测试
        btn_goto_culture.setEnabled(true);

        setCancelable(false);
    }

    private int getPosition(byte direction) {
        int position = 0;
        if (direction == PeristalticPumpBO.directionForward) {
            position = 0;
        } else if (direction == PeristalticPumpBO.directionReverse) {
            position = 1;
        }
        return position;
    }

    @OnClick({R.id.btn_edit_environment,R.id.edit_device_params,R.id.btn_set_environment,R.id.save_device_params,R.id.btn_goto_culture})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_edit_environment:
                btn_edit_environment.setVisibility(View.INVISIBLE);
                btn_set_environment.setVisibility(View.VISIBLE);
                ableEnvironmentParams(true);
                break;
            case R.id.edit_device_params:
                btn_edit_device_params.setVisibility(View.INVISIBLE);
                save_device_params.setVisibility(View.VISIBLE);
                ableDeviceParams(true);
                break;
            case R.id.btn_set_environment:
                String err1=checkEnvironment();
                if(err1==null){
                    paramsPresenter.setEnvironment();
                }else {
                    showDialogMessage("",err1);
                }
                break;
            case R.id.save_device_params:
                String err2=checkDeviceParams();
                if(err2==null){
                    paramsPresenter.saveDeviceParams();
                }else {
                    showDialogMessage("",err2);
                }
                break;
            case R.id.btn_goto_culture:
                Intent intent=new Intent(getActivity(),ExperimentActivity.class);
                Bundle bundle=new Bundle();
                bundle.putBoolean("isNewPorject",true);
                intent.putExtras(bundle);
                startActivity(intent);
                getActivity().finish();
                break;
                default:break;
        }
    }

    private void ableEnvironmentParams(boolean able){
        etCO2.setEnabled(able);
        etO2.setEnabled(able);
        etTemperature.setEnabled(able);
    }

    private void ableDeviceParams(boolean able){
        etPumpFluidIntakeSpeed.setEnabled(able);
        spPumpFluidIntakeDirection.setClickable(able);
        etPumpCirculatingSpeed.setEnabled(able);
        spPumpCirculatingDirection.setClickable(able);
        etPumpWasteSpeed.setEnabled(able);
        spPumpWasteDirection.setClickable(able);
        etPumpReclaimSpeed.setEnabled(able);
        spPumpReclaimDirection.setClickable(able);
        etMagneticStirrerSpeed.setEnabled(able);
        etCultureTankSpeed.setEnabled(able);
        etChangeAirFrequency.setEnabled(able);
        etChangeAirAmount.setEnabled(able);
        etShakeTableTime.setEnabled(able);
    }

    private String checkDeviceParams() {
        String err = null;
        if (TextUtils.isEmpty(etCO2.getText())) {
            err = "请输入CO2";
        } else if (TextUtils.isEmpty(etO2.getText())) {
            err = "请输入O2";
        } else if (TextUtils.isEmpty(etTemperature.getText())) {
            err = "请输入温度";
        } else if (TextUtils.isEmpty(etPumpFluidIntakeSpeed.getText())) {
            err = "请输入进液泵转速";
        } else if (TextUtils.isEmpty(etPumpCirculatingSpeed.getText())) {
            err = "请输入循环泵转速";
        } else if (TextUtils.isEmpty(etPumpWasteSpeed.getText())) {
            err = "请输入废液泵转速";
        } else if (TextUtils.isEmpty(etPumpReclaimSpeed.getText())) {
            err = "请输入灌装泵转速";
        } else if (TextUtils.isEmpty(etMagneticStirrerSpeed.getText())) {
            err = "请输入磁力搅拌机";
        } else if (TextUtils.isEmpty(etCultureTankSpeed.getText())) {
            err = "请输入培养罐真空泵转速";
        }else if(getInputSpeed()>ParamConsts.maxPumpSpeed){
            err="进液泵最大泵速"+ParamConsts.maxPumpSpeed;
        }else if(getCirclatingSpeed()>ParamConsts.maxPumpSpeed){
            err="循环泵最大泵速"+ParamConsts.maxPumpSpeed;
        }else if(getWasteSpeed()>ParamConsts.maxPumpSpeed){
            err="废液泵最大泵速"+ParamConsts.maxPumpSpeed;
        }else if(getReclaimSpeed()>ParamConsts.maxPumpSpeed){
            err="罐装泵最大泵速"+ParamConsts.maxPumpSpeed;
        }else if(getStrrierSpeed()>ParamConsts.maxStirrerSpeed){
            err="磁力搅拌器最大转速"+ParamConsts.maxStirrerSpeed;
        }else if(getCultureSpeed()>ParamConsts.maxCultureSpeed){
            err="培养罐换气泵最大转速"+ParamConsts.maxCultureSpeed;
        }else if(TextUtils.isEmpty(etChangeAirFrequency.getText().toString())){
            err="请输入换气频率";
        }else if(TextUtils.isEmpty(etChangeAirAmount.getText().toString())){
            err="请输入换气量";
        }else if(TextUtils.isEmpty(etShakeTableTime.getText().toString())){
            err="请输入摇床时间";
        }else {
            int frequency= Integer.parseInt(etChangeAirFrequency.getText().toString());
            int amount= Integer.parseInt(etChangeAirAmount.getText().toString());
            int minGap=5;
            if(UtilHelpers.calculateTimeByAirAmount(amount)>frequency*60+minGap){
                err="换气频率太高或换气量太大";
            }
        }
        return err;
    }

    private String checkEnvironment(){
        String err = null;
        if(getCO2()>ParamConsts.maxCO2){
            err="CO2浓度最大"+ParamConsts.maxCO2;
        }else if(getCO2()<ParamConsts.minCO2){
            err="CO2浓度最小"+ParamConsts.minCO2;
        }else if(getO2()>ParamConsts.maxO2){
            err="O2浓度最大"+ParamConsts.maxO2;
        }else if(getO2()<ParamConsts.minO2){
            err="O2浓度最小"+ParamConsts.minO2;
        }else if(getTemperature()>ParamConsts.maxTemperature){
            err="温度最大"+ParamConsts.maxTemperature;
        }else if(getTemperature()<ParamConsts.minTemperature){
            err="温度最小"+ParamConsts.minTemperature;
        }
        return err;
    }

    @Override
    public double getCO2() {
        return Double.parseDouble(etCO2.getText().toString());
    }

    @Override
    public double getO2() {
        return Double.parseDouble(etO2.getText().toString());
    }

    @Override
    public double getTemperature() {
        return Double.parseDouble(etTemperature.getText().toString());
    }

    @Override
    public int getInputSpeed() {
        return Integer.parseInt(etPumpFluidIntakeSpeed.getText().toString());
    }

    @Override
    public byte getInputDirection() {
        return spPumpFluidIntakeDirection.getSelectedItemPosition() == 0 ? PeristalticPumpBO.directionForward : PeristalticPumpBO.directionReverse;
    }

    @Override
    public int getCirclatingSpeed() {
        return Integer.parseInt(etPumpCirculatingSpeed.getText().toString());
    }

    @Override
    public byte getCirclatingDirection() {
        return spPumpCirculatingDirection.getSelectedItemPosition() == 0 ? PeristalticPumpBO.directionForward : PeristalticPumpBO.directionReverse;
    }

    @Override
    public int getWasteSpeed() {
        return Integer.parseInt(etPumpWasteSpeed.getText().toString());
    }

    @Override
    public byte getWasteDirection() {
        return spPumpWasteDirection.getSelectedItemPosition() == 0 ? PeristalticPumpBO.directionForward : PeristalticPumpBO.directionReverse;
    }

    @Override
    public int getReclaimSpeed() {
        return Integer.parseInt(etPumpReclaimSpeed.getText().toString());
    }

    @Override
    public byte getReclaimDirection() {
        return spPumpReclaimDirection.getSelectedItemPosition() == 0 ? PeristalticPumpBO.directionForward : PeristalticPumpBO.directionReverse;
    }

    @Override
    public int getStrrierSpeed() {
        return Integer.parseInt(etMagneticStirrerSpeed.getText().toString());
    }

    @Override
    public int getCultureSpeed() {
        return Integer.parseInt(etCultureTankSpeed.getText().toString());
    }

    @Override
    public int getChangeAirFrequency() {
        return Integer.parseInt(etChangeAirFrequency.getText().toString());
    }

    @Override
    public int getChangeAirAmount() {
        return Integer.parseInt(etChangeAirAmount.getText().toString());
    }

    @Override
    public int getShakeTableTime() {
        return Integer.parseInt(etShakeTableTime.getText().toString());
    }

    @Override
    public void onSetCO2Succ(CO2BO event) {
    }

    @Override
    public void onSetCO2Failed(CO2BO event) {
        showToast("CO2设置失败");
    }

    @Override
    public void onSetO2Succ(O2BO event) {
    }

    @Override
    public void onSetO2Failed(O2BO event) {
        showToast("O2设置失败");
    }

    @Override
    public void onSetTemperatureSucc(TemperatureBO event) {
    }

    @Override
    public void onSetTemperatureFailed(TemperatureBO event) {
        showToast("温度设置失败");
    }

    @Override
    public void onSaveDeviceParamsSucc() {
        showDialogMessage(null,"设备参数设置成功");
        isDeviceParamsSetted=true;
        btn_edit_device_params.setVisibility(View.VISIBLE);
        save_device_params.setVisibility(View.INVISIBLE);
        ableDeviceParams(false);
        if(isEnvironmentSetted){
            btn_goto_culture.setEnabled(true);
        }
    }

    @Override
    public void onSetEnvironmentSucc() {
        showDialogMessage(null,"环境状态设置成功");
        isEnvironmentSetted=true;
        btn_edit_environment.setVisibility(View.VISIBLE);
        btn_set_environment.setVisibility(View.INVISIBLE);
        ableEnvironmentParams(false);
        if(isDeviceParamsSetted){
            btn_goto_culture.setEnabled(true);
        }
    }

    @Override
    public void onNumberMax(String number, EditText editText) {
        initPopWindownIfNeed(number);
        if (rockPop.getPopupWindow().isShowing()&&editText==oldEditText) {
            return;
        }
        rockPop.show(editText);
        popDisposable = Observable.interval(1, TimeUnit.SECONDS)
                .take(2)
                .subscribeOn(Schedulers.newThread())
                .map(new Function<Long, Integer>() {
                    @Override
                    public Integer apply(Long aLong) throws Exception {
                        return 1 - aLong.intValue();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer integer) throws Exception {
                        if (integer <= 0) {
                            rockPop.dismiss();
                        }
                    }
                });
        oldEditText=editText;
    }

    private void initPopWindownIfNeed(String max) {
        if (rockPop == null) {
            View contentView = LayoutInflater.from(mContext).inflate(R.layout.rock_popup, null, false);
            TextView textView = contentView.findViewById(R.id.textView);
            textView.setText("最大值" + max);
            rockPop = new RockPop.PopupWindowBuilder(mContext)
                    .setView(contentView)
                    .setFocusable(false)
                    .setOutsideTouchable(false)
                    .setOnDissmissListener(new PopupWindow.OnDismissListener() {
                        @Override
                        public void onDismiss() {
                            if (popDisposable.isDisposed()) {
                                popDisposable.dispose();
                            }
                        }
                    })
                    .setDirection(RockPop.DIRECTION_TOP)
                    .create();
        } else {
            ((TextView) rockPop.getPopupWindow().getContentView().findViewById(R.id.textView)).setText("最大值" + max);
        }
    }

}
